package com.samsung.common.interceptor;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.samsung.common.annotation.LoginAuth;
import com.samsung.common.util.BaseUtil;
import com.samsung.common.util.Constant;

/**
 * 
 *	@ClassName: AuthInterceptor
 *	@Description: 普通页面请求拦截器，适用于控制器方法，使用时在相应方法上添加@LoginAuth注解即可
 *	@author pu.huang
 *	@date 2015年4月26日 上午10:22:44
 *
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			LoginAuth authPassport = ((HandlerMethod) handler).getMethodAnnotation(LoginAuth.class);

			
			// 没有声明需要权限,或者声明不验证权限
			if (authPassport == null || authPassport.validate() == false) {
				return true;
			} else {
				// 权限验证逻辑
				if (request.getSession().getAttribute(Constant.LOGIN_TOKEN) != null) {
					return true;
				} else {
					// 如果验证失败 返回到登录界面
					response.setDateHeader("expries", -1);
					response.setHeader("Cache-Control", "no-cache");
					response.setHeader("Pragma", "no-cache");
					StringBuffer cb = request.getRequestURL();
					String parms = request.getQueryString();
					if(BaseUtil.isNotEmpty(parms)) {
						cb.append("?");
						cb.append(parms);
					}
					StringBuffer url = new StringBuffer(request.getContextPath());
					url.append("/user/loginPage.html");
					if(BaseUtil.isNotEmpty(cb.toString())) {
						url.append("?callback=");
						url.append(URLEncoder.encode(cb.toString(), "UTF-8"));
						url.append("&r=");
						url.append(Math.random());
					}
					response.sendRedirect(url.toString());
					return false;
				}
			}
		} else {
			return true;
		}
	}
}